import { useEffect, useState } from "react";
import InfoPreview from "../../../infoPreview/InfoPreview";
import Button from "../../../ui/button/Button";
import Card from "../../../ui/card/Card";
import Input from "../../../ui/input/Input";
import InputFile from "../../../ui/inputFile/InputFile";

import classes from "./RequestFormSent.module.scss";
import useApi from "../../../../apis/hooks/useApi";
import { postCreateMessage } from "../../../../apis/sections/applicationView";
import useGetApiConfig from "../../../../apis/hooks/useGetApiConfig";
import useGlobalSpinner from "../../../../hooks/useGlobalSpinner";
import { useParams } from "react-router-dom";

const RequestFormSent = ({
  recipientId,
  updateMessageList,
  isMessageListPending,
}) => {
  const config = useGetApiConfig();
  const { applicationId } = useParams();
  const [messageText, setMessageText] = useState("");
  const [uploadFiles, setUploadFiles] = useState([]);

  const {
    exec: createMessageExec,
    isPending,
    apiStatus,
  } = useApi(() =>
    postCreateMessage(
      config,
      `?to=${encodeURIComponent(
        recipientId
      )}&applicationNumber=${encodeURIComponent(
        applicationId
      )}&message=${encodeURIComponent(messageText)}`,
      uploadFiles
    )
  );

  useGlobalSpinner(isPending || isMessageListPending);

  const sendMessageHandler = async () => {
    const { data } = await createMessageExec();

    if (data?.status === 0) {
      setMessageText("");
      setUploadFiles([]);
      updateMessageList();
    }
  };

  return (
    <Card className={classes["request-form"]}>
      <div className={classes["request-form-item"]}>
        <InfoPreview
          label={"Написать сообщение:"}
          labelClass={`${classes["label-sent-form"]} mb-10`}
          className={`${classes["sent-form"]} mr-40`}
        >
          <Input
            id={"registrationAddress"}
            placeholder={"Написать сообщение..."}
            isTextArea
            rows={3}
            value={messageText}
            isReadOnly={false}
            onChange={(e) => setMessageText(e.target.value)}
          />
          <Button className="mt-20" onClick={() => sendMessageHandler()}>
            Отправить
          </Button>
        </InfoPreview>

        <InfoPreview
          label={"Добавить файл"}
          className={`${classes["sent-form"]}`}
          labelClass="mb-10"
        >
          <InputFile
            attachedBinaryFiles={uploadFiles}
            setAttachedBinaryFiles={(file) => setUploadFiles(file)}
            multipleFiles
          />
        </InfoPreview>
      </div>
    </Card>
  );
};

export default RequestFormSent;